package entity

import (
	"center-platform/internal/controller/v1/user/entity"
	"center-platform/utils"
	"gorm.io/gorm"
	"time"
)

type Comment struct {
	ID         int       `json:"id" gorm:"column:id"`
	Content    string    `json:"content" gorm:"column:content" binding:"required"`
	UserID     int       `json:"user_id" gorm:"column:user_id;foreignKey:UserId"`
	PostID     int       `json:"post_id" gorm:"column:post_id"`
	LikeCount  int       `json:"like_count" gorm:"column:like_count;default:0"`
	ShareCount int       `json:"share_count" gorm:"column:share_count;default:0"`
	Status     int8      `json:"status" gorm:"column:status;default:0"` // 0-待审核 1-正常  -1-已删除
	CreatedAt  time.Time `json:"created_at" gorm:"column:created_at"`
	UpdatedAt  time.Time `json:"updated_at" gorm:"column:updated_at"`

	User entity.UserBasicInfoResponse `json:"user"`
}

type SearchParam struct {
	PostIds  []int  `json:"post_ids" binding:"required"`
	UserIds  []int  `json:"user_ids"`
	Status   []int8 `json:"status"`
	Page     int    `json:"page" binding:"required" validate:"min:1"`
	PageSize int    `json:"page_size" binding:"required" validate:"min:1"`
}

func (c *Comment) Create() error {
	err := utils.DB.Model(c).Omit("User").Create(c).Error
	if err != nil {
		return err
	}
	return nil
}

func (c *Comment) List(where interface{}, offset int, limit int, args ...interface{}) (error, []Comment) {
	var results []Comment
	err := utils.DB.Model(c).Preload("User").Where(where, args...).Offset(offset).Limit(limit).Find(&results).Error
	if err != nil {
		return err, nil
	}
	return nil, results
}

func (c *Comment) Update(where interface{}, update map[string]interface{}, args ...interface{}) error {
	err := utils.DB.Model(c).Where(where, args...).Updates(update).Error
	if err != nil {
		return err
	}
	return nil
}

func (c *Comment) Delete(where string, args ...interface{}) error {
	if len(where) == 0 {
		return gorm.ErrMissingWhereClause
	}
	if err := utils.DB.Where(where, args...).Delete(c).Error; err != nil {
		return err
	}
	return nil
}
